﻿/*
 * Created by SharpDevelop.
 * User: Corrado Mio
 * Date: 14/06/2012
 * Time: 21:24
 * 
 * 
 * Puo' essere usato in uno statement del tipo:
 * 
 *      using(DataTransaction dt = conn.UsingTransaction(...))
 *      {
 *          
 *          ...
 *          dt.Commit();
 *          ...
 *          dt.Rollback();
 *      }
 * 
 * Se non viene esplicitamente fatto il commit, all'uscita del blocco
 * viene fatto il rollback.
 */
using System;
using System.Data.Common;

namespace CSharpExt.Data
{
    /// <summary>
    /// Description of DataTransaction.
    /// </summary>
    public class DataTransaction : IDisposable
    {
        #region Private Data
        
        private DataConnection _conn;
        
        private DbTransaction _trans;
        
        private bool _commit;
        
        private bool _deferred;
        
        #endregion
        
        #region Constructor
        
        internal DataTransaction(DataConnection conn, DbTransaction trans)
        {
            _conn = conn;
            _trans = trans;
        }
        
        #endregion
        
        #region Properties
        
        internal bool Deferred
        {
            set { _deferred = value; }
        }
        
        #endregion
        
        #region Operations
        
        public void Commit()
        {
            if(_deferred)
            {
                _commit = true;
            }
            else
            {
                _trans.Commit();

                _conn.removeTransactions(this);
            }
        }
        
        public void Rollback()
        {
            if(_deferred)
            {
                _commit = false;
            }
            else
            {
                _trans.Rollback();
                
                _conn.removeTransactions(this);
            }
                
        }
        
        public void Close()
        {
            if(!_deferred)
                return;
            
            if (_commit)
                _trans.Commit();
            else
                _trans.Rollback();
            
            _conn.removeTransactions(this);
        }
        
        #endregion

        #region IDisposable
        
        public void Dispose()
        {
            Close();
        }
        
        #endregion
        
    }
}
